from flask import Blueprint, jsonify, request, render_template, session

from config import db
from models.models import Comments

comment_service = Blueprint("comment_service", __name__)


@comment_service.before_request
def session_checker():
    if 'user_id' not in session:
        return render_template('401.html')


@comment_service.route("/save/comment", methods=['POST'])
def save_comment():
    try:
        data = request.get_json()
        good_id = data.get('good_id')
        username = data.get('username')
        comment = data.get('comment')
        star = data.get('star')
        comment_time = data.get('comment_time')

        new_comment = Comments(
            good_id=good_id,
            username=username,
            star=star,
            comment_time=comment_time,
            comment=comment
        )
        db.session.add(new_comment)
        db.session.commit()

        return jsonify({"message": "评论已成功保存到数据库"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@comment_service.route("/get/comment/<int:_id>", methods=['POST'])
def get_comment(_id):
    types = Comments.query.filter_by(good_id=_id)
    data = []
    for _type in types:
        value = {
            'good_id': _type.id,
            'username': _type.username,
            'star': _type.star,
            'comment_time': _type.comment_time,
            'comment': _type.comment,
        }
        data.append(value)
    return jsonify({'data': data, 'code': 0})
